/*
 * BanBu_DialogueController
 * @description 本文件提供对话列表界面和来访记录的viewtroller
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供对话和来访记录的viewtroller
 */


#import "BanBu_DialogueController.h"
#import "BanBu_DialogueCell.h"
#import "BanBu_ChatViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "CJSONSerializer.h"
#import "NSDictionary_JSONExtensions.h"
#import <CommonCrypto/CommonDigest.h>
#import "CJSONDeserializer.h"
#import "LeveyTabBarController.h"
#import "BanBu_ImageView.h"
#import "BanBu_NavButton.h"
#import "BanBu_ListCell.h"
#import "BanBu_SecondaryDialogueViewController.h"
#import "BanBu_DynamicController.h"
#import "BanBu_ThemeManager.h"
#import "SVSegmentedControl.h"
//#import "Banbu_NopushView.h"

@interface BanBu_DialogueController ()

@end

@implementation BanBu_DialogueController

- (id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheme) name:kThemeDidChangeNotification object:nil];
    
    _showTalkView = YES;
    self.alreadyRefresh = YES;
    self.existUserIDDic = [NSMutableDictionary dictionary];
    
    self.deletDic = [NSMutableDictionary dictionaryWithCapacity:20];
    
    _isPush = YES;
    
    self.moreView = [[[UIView alloc]init]autorelease];
    lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320,20)];
    lab.font= [UIFont systemFontOfSize:15];
    lab.backgroundColor = [UIColor clearColor];
    
    lab.textAlignment = kTextAlignmentCenter;
    lab.textColor = [UIColor grayColor];
    [self.moreView addSubview:lab];
    
    UIActivityIndicatorView *act =  [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activeInditor = act;
    [act release];
    self.activeInditor.hidden = NO;
    [self.activeInditor setHidesWhenStopped:YES];
    self.activeInditor.frame = CGRectMake(0, 0, 50, 50);
    self.activeInditor.center = CGPointMake(160-([NSLocalizedString(@"loadingNotice", nil) sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 20) lineBreakMode:kTextLineBreakByWordWrapping].width/2)-15, 20);
    [self.activeInditor startAnimating];
    [self.moreView addSubview:self.activeInditor];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-88) style:UITableViewStylePlain];
    self.tableView = tableView;
    
    [self.view addSubview:tableView];
    [tableView release];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;   
    
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:self.tableView];
    
    [self createClearButton];
    [self createDeleteButton];
    segmentController = [[AKSegmentedControl alloc] initWithFrame:CGRectMake(5,5,196,34)];
    [segmentController setDelegate:self];
    [self setupSegmentedControl];
//    [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"isNewRegister"];//新注册用户
//    if([[UserDefaults valueForKey:@"isNewRegister"] boolValue])
//    {
//        [self createHeaderView];
//    }
    
}
//- (void)createHeaderView
//{
//    Banbu_NopushView *noprofile = [Banbu_NopushView shareView];
//    noprofile.frame = CGRectMake(0, 0, 320, 50);
//    [noprofile setNoticeType:NoticeOpenTypeImproveProfile];
//    self.tableView.tableHeaderView = noprofile;
//    
//    __block Banbu_NopushView *profile = noprofile;
//    [profile setDismiss:^(UIButton *btn) {
//        
//        CGRect frame = self.tableView.frame;
//        
//        [UIView animateWithDuration:0.2f animations:^{
//            CGRect f = frame;
//            f.origin.y = f.origin.y - 50;
//            self.tableView.frame = f;
//        } completion:^(BOOL finished) {
//            self.tableView.tableHeaderView = nil;
//
//            self.tableView.frame = frame;
//            [self.tableView reloadData];
//        }];
//        
//    }];
//    [profile setOpen:^(UIButton *btn) {
//        BanBu_PersonDataViewController *myProfile1 = [[BanBu_PersonDataViewController alloc] initWithProfile:[UserDefaults valueForKey:MyAppDataManager.useruid]];
//        [UserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"isNewRegister"];//新注册用户
//        [self.navigationController pushViewController:myProfile1 animated:YES];
//        [myProfile1 release];
//        [self performSelector:@selector(emptyHeader) withObject:nil afterDelay:0.2];
//        [self.tableView reloadData];
//    }];
//
//}
-(void)emptyHeader
{
    self.tableView.tableHeaderView = nil;
}
-(void)viewWillAppear:(BOOL)animated
{
    self.sliding = YES;
    _showTalkView = YES;
    [super viewWillAppear:animated];
    [self.leveyTabBarController hidesTabBar:NO animated:YES];
    self.alreadyRefresh = YES;
    self.existUserIDDic = [NSMutableDictionary dictionary];
    if (_isPush == YES) //
    {
        MyAppDataManager.totalLoadedPeopleNum = 20;
    }
    self.isLoading = NO;
    
    [self updateBadgeShow];
    
    _isPush = YES;
    self.tableView.editing = NO;
    
    //动画消失BUG
    [UIView setAnimationsEnabled:YES];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.moreView setFrame:CGRectMake(0, 0, 320, 90)];
    [self.moreView setBackgroundColor:[UIColor clearColor]];
    self.tableView.tableFooterView = self.moreView;
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.tableView.editing = NO;
    self.noData = NO;
    lab.text = NSLocalizedString(@"pullLoadMore", nil);
    [super viewWillDisappear:animated];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)dealloc
{
    [_existUserIDDic release],_existUserIDDic = nil;
    [_aCacheArray release],_aCacheArray = nil;
    
    [_moreView release],_moreView = nil;
    [_activeInditor release],_activeInditor = nil;
    
    [_deletDic release],_deletDic = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)createClearButton
{
    //添加“清除标记”按钮
    BanBu_NavButton *clearButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    clearButton.position = ButtonPositionLeft;
    [clearButton setImage:[UIImage imageNamed:@"DialogClearButton.png"] forState:UIControlStateNormal];
    clearButton.frame=CGRectMake(0, 0,40, 30);
    [clearButton addTarget:self action:@selector(clearFlag) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *clearItem = [[[UIBarButtonItem alloc] initWithCustomView:clearButton] autorelease];
    self.navigationItem.leftBarButtonItem = clearItem;
}

-(void)createDeleteButton
{
    //添加“删除”按钮
    deleteButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    deleteButton.position = ButtonPositionRight;
    deleteButton.frame=CGRectMake(0, 0,40, 30);
    deleteButton.tag = 101;
    [deleteButton addTarget:self action:@selector(editTable) forControlEvents:UIControlEventTouchUpInside];
    [deleteButton setImage:[UIImage imageNamed:@"deleteDialog.png"] forState:UIControlStateNormal];
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:deleteButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
}

-(void)editTable
{
    if (_slided)
    {
        return;
    }
    self.sliding = NO;
    
    [self setEditing:!self.tableView.editing animated:YES];
}

//修改tableView可编辑状态
- (void)setEditing:(BOOL)editting animated:(BOOL)animated
{
    if (self.slided)
    {
        self.tableView.editing = NO;
    }
    else
    {
        self.tableView.editing = !self.tableView.editing;
    }
    
	[super setEditing:!self.editing animated:YES];
    if(self.tableView.editing)
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        deleteButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        [deleteButton setImage:nil forState:UIControlStateNormal];
        [deleteButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    }
    else
    {
        self.sliding = YES;
        deleteButton.frame = CGRectMake(320-40-5, 7,40, 30);
        [deleteButton setTitle:nil forState:UIControlStateNormal];
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        [deleteButton setImage:[UIImage imageNamed:@"deleteDialog.png"] forState:UIControlStateNormal];
    }
    
    if(self.deletDic.count)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"deleteNotice", nil) activityAnimated:YES];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            NSMutableArray *tempArr = [NSMutableArray array];
            
            NSArray * talkpeoplesarray = [[NSArray alloc]initWithArray:MyAppDataManager.talkPeoples];
            
            //删除本地数据库中该人对话及聊天记录
            [MyAppDataManager deleteTalkPeople:self.deletDic.allKeys];
        
            NSInteger total = 0;
            
            NSMutableArray * userIDArray = [NSMutableArray arrayWithCapacity:20];
                        
            for(NSDictionary *aTalk in talkpeoplesarray)
            {
                total += [VALUE(KeyUnreadNum, aTalk) integerValue];

                if ([self.deletDic valueForKey:[aTalk valueForKey:KeyFromUid]])
                {
                    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[[self.deletDic valueForKey:[aTalk valueForKey:KeyFromUid]] integerValue] inSection:0];
                    
                    [userIDArray addObject:indexPath];
                    [tempArr addObject:aTalk];
                }
            }
            
            [talkpeoplesarray release];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",total],@"pushcount",nil];
            
            //提交推送
            [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:dic delegate:self];
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                //数据源删除
                MyAppDataManager.totalLoadedPeopleNum -=self.deletDic.count;
                [MyAppDataManager.talkPeoples removeObjectsInArray:tempArr];
                                                
                //界面删除
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:userIDArray withRowAnimation:UITableViewRowAnimationFade];
                [self.tableView endUpdates];
                
                _totalUnreadNum = [MyAppDataManager getBadgeValue];
                [self.leveyTabBarController.tabBar setBadgeValue:[NSString stringWithFormat:@"%i",_totalUnreadNum] withButtonIndex:2];
                [self setSegmentBadgeValue:_totalUnreadNum];
                //删除数组清空
                
                //当屏幕上显示对话数量小于10时重新载入20条
                if (MyAppDataManager.talkPeoples.count<10)
                {
                    [MyAppDataManager readTalkList:nil WithNumber:20];
                    [self.tableView reloadData];
                }
                
                if (MyAppDataManager.talkPeoples.count <=0)
                {
                    self.navigationItem.rightBarButtonItem = nil;
                }
                
                [self.deletDic removeAllObjects];
                [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0.0];
            });
        });
    }
}

-(void)changeTheme
{
    UIImage *backgroundImage = [ThemeManager getThemeImage:@"segmentTitle.png"];//[[ThemeManager getThemeImage:@"segmentTitle.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)];
    
    [segmentController setBackgroundImage:backgroundImage];
//    if(segmentController)
//    {
//        [segmentController release];
//    }
//    segmentController = [[AKSegmentedControl alloc] initWithFrame:CGRectMake(5,5,196,34)];
//    [segmentController setDelegate:self];
//    [self setupSegmentedControl];
}

- (void)setupSegmentedControl
{
    NSArray *titleArr = [NSArray arrayWithObjects:NSLocalizedString(@"dialogueTitle", nil),NSLocalizedString(@"visitorLabel", nil), nil];
    UIImage *backgroundImage = [ThemeManager getThemeImage:@"segmentTitle.png"];//[[ThemeManager getThemeImage:@"segmentTitle.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)];
    
    [segmentController setBackgroundImage:backgroundImage];
    [segmentController setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin];
    
    UIImage *buttonBackgroundImagePressed_left = [UIImage imageNamed:@"segmented-bg-pressed_left.png"];
    UIImage *buttonBackgroundImagePressed_right = [UIImage imageNamed:@"segmented-bg-pressed_right.png"];
    
    //对话Button
    UIButton *buttonTalk = [[[UIButton alloc] init] autorelease];
    [buttonTalk setTitle:[titleArr objectAtIndex:0] forState:UIControlStateNormal];
    [buttonTalk setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonTalk.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0]];
    
    [buttonTalk setBackgroundImage:buttonBackgroundImagePressed_left forState:UIControlStateHighlighted];
    [buttonTalk setBackgroundImage:buttonBackgroundImagePressed_left forState:UIControlStateSelected];
    [buttonTalk setBackgroundImage:buttonBackgroundImagePressed_left forState:(UIControlStateHighlighted|UIControlStateSelected)];
    
    UIImageView *lineview1 = [[UIImageView alloc] initWithFrame:CGRectMake(segmentController.frame.size.width/2, 0, 1, segmentController.frame.size.height)];
//    lineview1.image = [UIImage imageNamed:@"segmented-separator.png"];
    [buttonTalk addSubview:lineview1];
    [lineview1 release];
    
    // 来访记录Button
    UIButton *buttonVisit = [[[UIButton alloc] init] autorelease];
    
    [buttonVisit setTitle:[titleArr objectAtIndex:1] forState:UIControlStateNormal];
    [buttonVisit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonVisit.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0]];
    [buttonVisit setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 5.0, 0.0, 0.0)];
    
    [buttonVisit setBackgroundImage:buttonBackgroundImagePressed_right forState:UIControlStateHighlighted];
    [buttonVisit setBackgroundImage:buttonBackgroundImagePressed_right forState:UIControlStateSelected];
    [buttonVisit setBackgroundImage:buttonBackgroundImagePressed_right forState:(UIControlStateHighlighted|UIControlStateSelected)];
    
    friendOnline = [[UIImageView alloc] initWithFrame:CGRectMake(55,4, 8, 8)];
    [friendOnline setImage:[UIImage imageNamed:@"onlineFlag.png"]];
    [buttonVisit addSubview:friendOnline];
    friendOnline.hidden = YES;
    
    [segmentController setButtonsArray:@[buttonTalk, buttonVisit]];
    
    _badgeViewTalk = [[UIBadgeView alloc] init];
    
    _badgeViewTalk.backgroundColor = [UIColor clearColor];
    _badgeViewTalk.badgeColor = [UIColor redColor];
    [segmentController addSubview:_badgeViewTalk];
    
    //添加显示有新消息的图片
    _redImage = [[UIImageView alloc]initWithFrame:CGRectZero];
    _redImage.image = [UIImage imageNamed:@"noticeview.png"];
    [segmentController addSubview:_redImage];
    
    [self.navigationItem.titleView.superview bringSubviewToFront:self.navigationItem.titleView];
    self.navigationItem.titleView = segmentController;
}

//切到来访记录
-(void)exchangeTalkTableWithVisitRecord
{
    _showTalkView = NO;//不显示对话列表，只显示来访记录
    if (!_showTalkView)
    {
        MyAppDataManager.newRecord = NO;
        BanBu_DynamicController *dynamic = [[BanBu_DynamicController alloc]initWithDynamicDisplayType:DisplayVisitRecord];
        dynamic.fromDialog = YES;
        
        [self.navigationController pushViewController:dynamic animated:NO];
        [dynamic release];
        [segmentController setSelectedIndex:0];
    }
    _redImage.frame = CGRectZero;
}

//更新全局对话数量及气泡数字
- (void)updateBadgeShow
{
    if (_showTalkView)
    {
        if (MyAppDataManager.newRecord)
        {
            _redImage.frame = CGRectMake(segmentController.frame.size.width-10, -2, 10, 10);//来访记录按钮显示气泡
        }
        [self refreshTalkTableView];
    }
    else
    {
        //只刷新新消息数字，并在“对话”标题上显示气泡
        [self refreshUnReadNum];
    }
    
    [self setSegmentBadgeValue:_totalUnreadNum];
    NSNumber * UnReadnum = [NSNumber numberWithInt:_totalUnreadNum];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"setUnreadNumber" object:UnReadnum];
    
}

#pragma mark - 在对话标题上显示数量
//在标题按钮上显示
-(void)setSegmentBadgeValue:(NSInteger)talkValue
{
    NSString * talkStr = [NSString stringWithFormat:@"%d",talkValue];
    float width = [talkStr sizeWithFont:[UIFont boldSystemFontOfSize:14]].width+12;
    
    self.badgeViewTalk.badgeString = talkStr;
    self.badgeViewTalk.frame=CGRectMake(segmentController.frame.size.width/2-width+5, -2, width, 20);
    
    if(talkValue == 0)
    {
        self.badgeViewTalk.hidden = YES;
    }
    else
    {
        self.badgeViewTalk.hidden = NO;
    }    
}

#pragma mark - 接收到新消息
//刷新对话列表
-(void)refreshTalkTableView
{
    //新消息来时，table会刷新，列数会增加，但是MyAppDataManager.totalLoadedPeopleNum不会变
    [MyAppDataManager readTalkList:nil WithNumber:MyAppDataManager.totalLoadedPeopleNum];
    
    MyAppDataManager.totalLoadedPeopleNum = MyAppDataManager.talkPeoples.count;
    
    _totalUnreadNum = [MyAppDataManager getBadgeValue];
    
    if (self.alreadyRefresh)
    {
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    }
    else
    {
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    }
    
    [self.leveyTabBarController.tabBar setBadgeValue:[NSString stringWithFormat:@"%i",_totalUnreadNum] withButtonIndex:2];
    
    if (_totalUnreadNum)
    {
        [self createClearButton];
    }
    else
    {
        self.navigationItem.leftBarButtonItem = nil;
    }
    
    if (MyAppDataManager.talkPeoples.count)
    {
        [self createDeleteButton];
    }
    else
    {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

//只刷新对话列表的气泡
-(void)refreshUnReadNum
{
    //更新tabBar气泡
    
    _totalUnreadNum = [MyAppDataManager getBadgeValue];
    
    [self.leveyTabBarController.tabBar setBadgeValue:[NSString stringWithFormat:@"%i",_totalUnreadNum] withButtonIndex:2];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (MyAppDataManager.talkPeoples.count <=20)
    {
        NSLog(@"%d",MyAppDataManager.talkPeoples.count);
        return MyAppDataManager.talkPeoples.count;
    }
    return MyAppDataManager.totalLoadedPeopleNum;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    BanBu_DialogueCell *cell = (BanBu_DialogueCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[BanBu_DialogueCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSMutableDictionary *aTalk;
    if([MyAppDataManager.talkPeoples count] > indexPath.row)
    {
        aTalk = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.talkPeoples objectAtIndex:indexPath.row]];
    }
    else
    {
        aTalk = nil;
    }
    cell.sliding = NO;
    //设置距离
    [cell setDistance:[MyAppDataManager IsInternationalLanguage:VALUE(KeyDmeter, aTalk)]];
    [cell setAvatar:VALUE(KeyUface, aTalk)];
    if ([[aTalk valueForKey:KeyFromUid] integerValue] == 600)
    {
        NSDictionary * dic = [MyAppDataManager getTheLastSayHiUserinfo:@"600"];
        if (dic.count<=0)
        {
           dic = [MyAppDataManager getTheLastSayHiUserinfo:@"600"];
        }
        
        NSNumber * unreadNum = [[MyAppDataManager getUnreadNumBySayHi:@"600"] valueForKey:KeyUnreadNum];

        NSString * pName = [MyAppDataManager IsInternationalLanguage:NSLocalizedString(@"sayHi", nil)];
                
        [cell setName:pName];
        
        [aTalk setValue:unreadNum forKey:KeyUnreadNum];
        [aTalk setValue:[MyAppDataManager.lastSayHiUserInfoDic valueForKey:KeySex] forKey:KeySex];
        [aTalk setValue:[MyAppDataManager.lastSayHiUserInfoDic valueForKey:KeyDmeter] forKey:KeyDmeter];
        [aTalk setValue:[MyAppDataManager.lastSayHiUserInfoDic valueForKey:KeyOldyears] forKey:KeyOldyears];
        [aTalk setValue:[MyAppDataManager.lastSayHiUserInfoDic valueForKey:KeyContent] forKey:KeyContent];
        [aTalk setValue:[MyAppDataManager.lastSayHiUserInfoDic valueForKey:KeyStime] forKey:KeyStime];
    }
    else
    {
        [cell setName:[MyAppDataManager IsInternationalLanguage:VALUE(KeyUname, aTalk)]];
    }

    //设置时间
    [cell setLastInfo: VALUE(KeyStime, aTalk)];
    [cell setAge:VALUE(KeyAge, aTalk) sex:[VALUE(KeySex, aTalk) boolValue] verify:[[aTalk valueForKey:@"verify"] boolValue]];
    
    [cell setlastDialogue:VALUE(KeyLasttalk, aTalk) andType:[VALUE(KeyType, aTalk) intValue]];
    
    [cell setVIPFlag:[[aTalk valueForKey:@"userlevel"] integerValue]>0];
    [cell setVerify:![[aTalk valueForKey:@"verify"] isEqual:@"y"]];
    
    if(![VALUE(KeyLasttalk, aTalk) isEqualToString:@""])
    {
        if([VALUE(KeyMe, aTalk) boolValue])
        {
            if([aTalk valueForKey:@"status"])
            {
                if ([VALUE(KeyStatus, aTalk) intValue] == DialogueMessageStautusReadType)
                {
                    NSLog(@"已读");
                }
                [cell setReadAndSend:[VALUE(KeyStatus, aTalk) intValue]];
            }
        }
        else
        {
            [cell setReadAndSend:DialogueMessageStautusNoneType];
        }
//        cell.receiveAndsend.hidden = NO;
        [cell setReceiveAndSendButtonHidden:NO];
        [cell setReceiveAndsend11:[VALUE(KeyMe, aTalk) boolValue]];
    }
    else
    {
//        cell.receiveAndsend.hidden = YES;
        [cell setReceiveAndSendButtonHidden:YES];
        [cell setReadAndSend:DialogueMessageStautusNoneType];
    }
    
    if ([[aTalk valueForKey:KeyFromUid] integerValue] == 600)
    {
        
        [cell setNameLastSayHi:[MyAppDataManager IsInternationalLanguage:VALUE(KeyUname, MyAppDataManager.lastSayHiUserInfoDic)]];
    }
    else
    {
        [cell setNameLastSayHi:nil];
    }

    
    NSInteger unReadNum = [VALUE(KeyUnreadNum, aTalk) integerValue];
    
    [cell setBadageValue:[NSString stringWithFormat:@"%i",unReadNum]];

    //多选删除
     if([MyAppDataManager.talkPeoples count]>indexPath.row)
     {
         NSMutableDictionary *talkPeopleDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.talkPeoples objectAtIndex:indexPath.row]];
         BOOL isChecked = [[talkPeopleDic valueForKey:@"isChecked"] boolValue];
         
         [cell setChecked:isChecked];
         [self.existUserIDDic setValue:[NSNumber numberWithBool:YES] forKey:[aTalk valueForKey:KeyFromUid]];
         
         NSString * indexPath = [self.deletDic valueForKey:[aTalk valueForKey:KeyFromUid]];
         
         if (indexPath)
         {
             [cell setChecked:YES];
         }
     }
    
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.sliding)
    {
        BanBu_DialogueCell * cell = (BanBu_DialogueCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.sliding = self.sliding;
        _slided = YES;
        
        //怎么样才能好啊
        return UITableViewCellEditingStyleDelete;
    }
    else
    {
        return UITableViewCellEditingStyleNone;
    }
}

- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    _slided = NO;//滑动删除结束
}

//实现删除行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    _slided = NO;//滑动删除结束
    //从数据源中删除
    NSDictionary * aTalk = [MyAppDataManager.talkPeoples objectAtIndex:indexPath.row];
    
    if ([VALUE(KeyFromUid, aTalk) isEqualToString:@"600"])
    {//删除打招呼
        [MyAppDataManager deleteBlackDialog:@"600"];
        [MyAppDataManager clearAllSecondaryUserMsg:@"600" andUserArray:@[@"600"]];//删除打招呼
    }
    else
    {
        [MyAppDataManager deleteBlackDialog:VALUE(KeyFromUid, aTalk)];
    }
    
    [MyAppDataManager.talkPeoples removeObjectAtIndex:indexPath.row];
    
    //删除table中的行
    [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationFade];
    
    _totalUnreadNum = [MyAppDataManager getBadgeValue];
    [self.leveyTabBarController.tabBar setBadgeValue:[NSString stringWithFormat:@"%i",_totalUnreadNum] withButtonIndex:2];
    [self setSegmentBadgeValue:_totalUnreadNum];
}

#pragma mark - Table view delegate
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.tableView.editing)
    {
        NSMutableDictionary *talkPeopleDic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager.talkPeoples objectAtIndex:indexPath.row]];
        BOOL isChecked = [[talkPeopleDic valueForKey:@"isChecked"] boolValue];
                
        [talkPeopleDic setValue:[NSString stringWithFormat:@"%d",!isChecked] forKey:@"isChecked"];
        
        NSString * userid = [talkPeopleDic valueForKey:KeyFromUid];
        
        [MyAppDataManager.talkPeoples replaceObjectAtIndex:indexPath.row withObject:talkPeopleDic];
        
        BanBu_DialogueCell *cell = (BanBu_DialogueCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell setChecked:!isChecked];
        if(!isChecked)
        {
            [self.deletDic setValue:[NSString stringWithFormat:@"%d",indexPath.row] forKey:userid];
        }
        else
        {
            [self.deletDic removeObjectForKey:userid];
        }
    }
    else
    {
        NSDictionary *userDic = [NSDictionary dictionaryWithDictionary:[MyAppDataManager.talkPeoples objectAtIndex:indexPath.row]];
        // 判断这个用户的usrid 如果小于一个确定的数那么跳入到对应的
        if(_isPush)
        { //防止页面卡住时，多次点击该cell，会push多个viewcontroller
            //判断未读消息是否超过20条，因为默认只会读取20条记录
            
            if([VALUE(KeyUnreadNum, userDic) integerValue]!=0 && [[userDic valueForKey:@"userid"] intValue]!=600)
            {
                NSDictionary *unReadDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",0-[VALUE(KeyUnreadNum, userDic) integerValue]],@"pushcount",nil];
                
                [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:unReadDic delegate:self];
                
                //更改数据库，将这个人的未读条数清零
                [MyAppDataManager setUnreadNumber:0 With:[userDic valueForKey:@"userid"]];
                
                [MyAppDataManager.readedUserArray addObject:[userDic valueForKey:KeyFromUid]];
            }
            
            //发送已读状态
            if (AppComManager.netStatus!= NotReachable)
            {
                if (MyAppDataManager.readedUserArray.count > 1)
                {
                    [MyAppDataManager sendReadedStatus:MyAppDataManager.readedUserArray];
                    [MyAppDataManager.readedUserArray removeAllObjects];
                }
            }
            
            if([VALUE(KeyUnreadNum, userDic) integerValue]>5)
            {
                if ([VALUE(KeyUnreadNum, userDic) integerValue]<100)
                {
                    [MyAppDataManager readTalkList:[userDic valueForKey:@"userid"] WithNumber:[VALUE(KeyUnreadNum, userDic) integerValue]];
                }
                else
                {
                    [MyAppDataManager readTalkList:[userDic valueForKey:@"userid"] WithNumber:100];
                }
            }
            else
            {
                [MyAppDataManager readTalkList:[userDic valueForKey:@"userid"] WithNumber:5];
            }
            
            
            if ([[userDic valueForKey:@"userid"] intValue] == 600)
            {
                BanBu_SecondaryDialogueViewController * secondary = [[BanBu_SecondaryDialogueViewController alloc]init];
            
                [self.navigationController pushViewController:secondary animated:YES];
                [secondary release];
            }
            else
            {
                //彩蛋处理
                BOOL showEggs = NO;
                
                NSString * content = nil;
                NSInteger unReadNum = [VALUE(KeyUnreadNum, userDic) integerValue];
                if (unReadNum > 5)
                {
                    for (NSDictionary * amsg in MyAppDataManager.dialogs)
                    {
                        if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeText && ![[amsg valueForKey:KeyShowFrom] isEqualToString:@"snap"])
                        {
                            NSArray * array = [MyAppDataManager easteregg:VALUE(KeyContent, amsg)];
                            if (array)
                            {
                                showEggs = YES;
                                content = [amsg valueForKey:KeyContent];
                                break;
                            }
                        }
                    }
                }
                else
                {
                    //unReadNum为1；count：5
                    for (int i = MyAppDataManager.dialogs.count -1; i >= MyAppDataManager.dialogs.count - unReadNum && i>=0; i--)
                    {
                        NSDictionary * amsg = [MyAppDataManager.dialogs objectAtIndex:i];
                        
                        if ([[amsg valueForKey:KeyType] integerValue] == ChatCellTypeText && ![[amsg valueForKey:KeyShowFrom] isEqualToString:@"snap"])
                        {
                            NSArray * array = [MyAppDataManager easteregg:VALUE(KeyContent, amsg)];
                            if (array)
                            {
                                showEggs = YES;
                                content = [amsg valueForKey:KeyContent];
                                break;
                            }
                        }
                    }
                }
                
                BanBu_ChatViewController *chat = [[BanBu_ChatViewController alloc] initWithPeopleProfile:userDic];
                
                //是否显示headerview
                if([[userDic valueForKey:@"userid"] intValue]<1000)
                {
                    chat.hidHeader = YES;
                }
                else
                {
                    chat.hidHeader = NO;
                }
                _isPush = NO;
                
                chat.returnBtTitle = @"dialogueTitle";//设置聊天界面返回按钮显示为“对话”
                
                chat.smileViewBackup = MyAppDataManager.smileViewBackup;
                chat.content = content;
                
                [self.navigationController pushViewController:chat animated:YES];
                [chat release];
            }
        }
    }
 }


-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(cell)
    {
        [(BanBu_ListCell*)cell cancelImageLoad];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(self.tableView.contentOffset.y>self.tableView.contentSize.height-__MainScreen_Height+44+45)
    {
        self.alreadyRefresh = NO;
        if(!self.isLoading)
        {
            self.isLoading = YES;
            [self startLoadNextPage];
        }
    }
}

-(void)startLoadNextPage
{
    //缓存中没有数据时,去加载数据
    
    self.aCacheArray = [MyAppDataManager readTalkListAfterSendImage:nil WithNumber:MyAppDataManager.totalLoadedPeopleNum];
    //去重
    [self removeReiteration];
    
    if (self.aCacheArray.count)
    {
        self.noData = NO;
        [MyAppDataManager.talkPeoples addObjectsFromArray:self.aCacheArray];

        MyAppDataManager.totalLoadedPeopleNum = MyAppDataManager.talkPeoples.count;

        [self.aCacheArray removeAllObjects];
        
        [self.tableView reloadData];
        
        self.alreadyRefresh = YES;
        self.isLoading = NO;
    }
    else
    {
        lab.text = NSLocalizedString(@"noData", nil);
        self.noData = YES;
        [self.activeInditor stopAnimating];
        self.isLoading = NO;
        return;
    }
}

//移除已经在界面上显示的用户
-(void)removeReiteration
{
    NSMutableDictionary * dica = [NSMutableDictionary dictionaryWithDictionary:self.existUserIDDic];
    NSArray * array = [NSArray arrayWithArray:self.aCacheArray];
    for (NSDictionary * dic in array)
    {
        if (self.aCacheArray.count == 0)
        {
            break;
        }
        NSString * userid = [dic valueForKey:KeyFromUid];
        
        if ([dica valueForKey:userid])
        {
            [self.aCacheArray removeObject:dic];
        }
        else if ([userid integerValue]==500 && [[dic valueForKey:KeyUnreadNum] integerValue] != 0)
        {
            [MyAppDataManager.talkPeoples insertObject:dic atIndex:0];
            [self.aCacheArray removeObject:dic];
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqual:@"contentOffset"])
    {
        if(![lab.text isEqual:NSLocalizedString(@"loadingMore", nil)]&&self.tableView.contentOffset.y>self.tableView.contentSize.height-__MainScreen_Height+44+45)
        {
            if(!self.isLoading)
                lab.text = NSLocalizedString(@"loadingMore", nil);
            [self.activeInditor startAnimating];
        }
        else if(![lab.text isEqual:NSLocalizedString(@"pullLoadMore", nil)]&&self.tableView.contentOffset.y<=self.tableView.contentSize.height-__MainScreen_Height+44+45)
        {
            if ([lab.text isEqualToString:NSLocalizedString(@"noData", nil)])
            {
                return;
            }
            else
            {
                if (!self.isLoading)
                    lab.text = NSLocalizedString(@"pullLoadMore", nil);
                [self.activeInditor stopAnimating];
            }            
        }
        
        if (self.noData)
        {
            lab.text = NSLocalizedString(@"noData", nil);
            [self.activeInditor stopAnimating];
        }
        
        if (self.tableView.contentSize.height < 460)
        {
            self.moreView.hidden = YES;
        }
        else
        {
            self.moreView.hidden = NO;
        }
        
        if (MyAppDataManager.talkPeoples.count<10)
        {
            self.moreView.hidden = YES;
        }
    }
}

//清除标记
- (void)clearFlag
{
    if (_totalUnreadNum == 0)
    {
        return;
    }
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"clearButton", nil) message:NSLocalizedString(@"clearFlagOrNot", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    
    alert.tag = 101;
    [alert show];
    [alert release];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
            return;
            break;
        case 1:
            //清除标记也要告知服务器。
            if(_totalUnreadNum)
            {
                [MyAppDataManager setUnreadNumber:0 With:nil];
                
                _totalUnreadNum = 0;
                [self.leveyTabBarController.tabBar setBadgeValue:@"0" withButtonIndex:2];
                
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"pushcount",nil];
                
                [AppComManager getBanBuData:Banbu_Set_User_Pushcount par:dic delegate:self];
                
                [MyAppDataManager readTalkList:nil WithNumber:MyAppDataManager.totalLoadedPeopleNum];
                
                [self.tableView reloadData];
                self.navigationItem.leftBarButtonItem = nil;
                
                [self setSegmentBadgeValue:_totalUnreadNum];
            }

            break;
        default:
            return;
            break;
    }
}

#pragma mark -
#pragma mark AKSegmentedControlDelegate

- (void)segmentedViewController:(AKSegmentedControl *)segmentedControl touchedAtIndex:(NSUInteger)index
{
    if(index == 1)
    {
        [self exchangeTalkTableWithVisitRecord];
    }
    selectIndex = index;
}


@end
